package com.jt.controller;

import com.alibaba.dubbo.config.annotation.Reference;
import com.jt.pojo.Cart;
import com.jt.pojo.User;
import com.jt.service.DubboCartService;
import com.jt.util.UserThreadLocal;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import java.util.List;

@Controller
@RequestMapping("/cart")
public class CartController {

    private static final String JTUSER = "JT_USER";

    @Reference(check = false)
    private DubboCartService cartService;

    /**
     * 修改购物车中商品数量
     * 1.url地址：http://www.jt.com/cart/update/num/562379/5
     * 2.参数：itemId/num
     * 3.返回值:void
     * 条件：userId = 7 暂时写死
     */
    @RequestMapping("/update/num/{itemId}/{num}")
    @ResponseBody
    public void updateCart(Cart cart){//如果restful中的参数与对象的属性一致
//        Long userId = 7L;
        Long userId = UserThreadLocal.get().getId();
        cart.setUserId(userId);
        cartService.updateCartNum(cart);
    }

    /**
     * 购物车列表数据展现
     * url:
     * 参数:无
     * 返回值： cart 页面逻辑名称
     * 页面取值数据:${cartList}
     * 业务核心流程:根据userId查询购物车记录   userId=7
     */
    @RequestMapping("/show")
    public String show(Model model, HttpServletRequest request){
        //自定义userId 后期维护
//        Long userId = 7L;
        User user = (User) request.getAttribute(JTUSER);
        Long userId = user.getId();
        List<Cart> cartList = cartService.findCartListByUserId(userId);
        model.addAttribute("cartList",cartList);
        return "cart";
    }

    /**
     * 删除购物车商品
     * 1.url地址:http://www.jt.com/cart/delete/562379.html
     * 2.参数：itemId
     * 3.返回值：重定向到购物车列表页面
     */
    @RequestMapping("/delete/{itemId}")
    public String deleteCart(Cart cart){
        //1.动态获取userId
//        Long userId = 7L;
        Long userId = UserThreadLocal.get().getId();
        cart.setUserId(userId);
        //2.执行删除业务
        cartService.deleteCart(cart);
        return "redirect:/cart/show.html";
    }

    /**
     * 新增购物车商品
     * 1.url地址:http://www.jt.com/cart/add/562379.html
     * 2.参数：表单数据提交   cart
     * 3.返回值：重定向到购物车列表页面
     * 注意事项：  如果用户重复添加购物车则只修改数量即可
     */
    @RequestMapping("/add/{itemId}")
    public String saveCart(Cart cart){
//        Long userId = 7L;
        Long userId = UserThreadLocal.get().getId();
        cart.setUserId(userId);
        cartService.saveCart(cart);
        return "redirect:/cart/show.html";
    }
}
